# -*- coding: utf-8 -*-
import odoorpc
from openerp.tools.float_utils import float_compare, float_round, float_is_zero
import datetime
def GetOdooConnect():
    odoo = odoorpc.ODOO('localhost', port=8069)
    odoo.login('ss', 'admin', 'admin')
    return odoo


def get_quant_ids(odoo, move):
    quant_obj = odoo.env['stock.quant']
    orderby = 'in_date'
    domain = [('qty', '>', 0),
              ('product_id', '=', move.product_id.id),
              ('location_id', 'child_of', move.location_id.id),
              ('reservation_id', '=', False)]
    if move.origin_returned_move_id:
        domain += [('history_ids', 'in', move.origin_returned_move_id.id)]
    all_quant_ids = quant_obj.search(domain, order=orderby, limit=10)
    quant_ids = []
    product_uom_qty = move.product_uom_qty
    if product_uom_qty and not all_quant_ids:
        move.write({'quant_ids': [(False, False, {
            'product_id': move.product_id.id,
            'qty': product_uom_qty,
            'location_id': move.location_dest_id.id,
            'in_date': str(move.date),
            'prod_spec': False})]})
    for quant in quant_obj.browse(all_quant_ids):
        if product_uom_qty == 0:
            break
        if float_is_zero(quant.qty-product_uom_qty, 0, 2):
            quant.write({'location_id': move.location_dest_id.id})
            quant_ids.append(quant.id)
            break
        elif float_compare(product_uom_qty-quant.qty, 0, 2) > 0:
            quant.write({'location_id': move.location_dest_id.id})
            quant_ids.append(quant.id)
            product_uom_qty = product_uom_qty - quant.qty
        else:
            quant_ids.append(quant.id)
            quant_obj.create({'product_id': quant.product_id.id,
                              'qty': quant.qty - product_uom_qty,
                              'location_id': quant.location_id.id,
                              'in_date': str(quant.in_date),
                              'prod_spec': False})
            quant.write({'location_id': move.location_dest_id.id,
                         'qty': product_uom_qty})
            break
    return quant_ids

def GetInternalStock(odoo):
    move_obj = odoo.env['stock.move']
    move_ids = move_obj.search([('state', '=', 'done'), ('product_id', '=', 13499)], order='date asc')
    for move in move_obj.browse(move_ids):
        quant_ids = get_quant_ids(odoo, move)
        move.write({'quant_ids': [(4, quant_id) for quant_id in quant_ids]})

if __name__ == "__main__":
    odoo = GetOdooConnect()
    GetInternalStock(odoo)
